/* 
 * File:   TerrainRenderer.cpp
 * Author: Nick
 * 
 * Created on 13 April 2011, 9:24 PM
 */

#include "TerrainRenderer.h"
#include "GameData.h"
#include "SceneModel.h"
#include "Terrain.h"
#include "BlockRenderer.h"
#include <gl/GL.h>


TerrainRenderer::TerrainRenderer(GameData* data) {
    this->_data = data;
    _first_render = true;
    _rendered_version = -1;
}

TerrainRenderer::~TerrainRenderer() {
}

void TerrainRenderer::draw() {


    GLfloat scale = 10000;
    glScaled(scale,scale,scale);

    UNIT rc[3*WORLD_DEPTH];
    _data->scene_model()->get_root_coord(rc);

    for( int d = 2; d < 7; d++){
        int d3 = d*3;
//        if(_first_render){
//            printf("root_coord:%d,%d,%d\n",-rc[d3],-rc[d3+1],-rc[d3+2]);
//            printf("root_node_pos:%d,%d,%d\n",_data->scene_model()->roots[d]->pos[0],_data->scene_model()->roots[d]->pos[1],_data->scene_model()->roots[d]->pos[2]);
//        }
        glTranslatef(-rc[d3],-rc[d3+1],-rc[d3+2]);
        glScalef(0.1,0.1,0.1);
    }
    for( int d = 2; d < 7; d++){
         glScalef(10,10,10);
    }

    if(_rendered_version == _data->scene_model()->get_version()){
        return;
    }

    glLineWidth(1);
    glColor3d(1,0,0);

    Block*  block = _data->scene_model()->roots[2];
    Cell*   cell = null;
    Cell*   stack[10] = {0};
    int     depth = 0;


    while(block != null){
        glTranslatef(block->pos[0],block->pos[1],block->pos[2]);
        if(_first_render){ block->check_draw();}
        block->draw();

        if(block->get_type() == BLOCK_TYPE_CELL){
            cell = static_cast<Cell*>(block);

            if(cell->first != null){
//                if(_first_render){printf("down:%d\n",depth);}
                stack[depth++] = cell;
                glScaled(0.1,0.1,0.1);
                block = cell->first;
                continue;
            }
            if(cell->next != null){
//                if(_first_render){printf("next\n");}
                glTranslatef(-block->pos[0],-block->pos[1],-block->pos[2]);
                block = block->next;
                continue;
            }
            glTranslatef(-block->pos[0],-block->pos[1],-block->pos[2]);
            while(cell->next == null){
//                if(_first_render){printf("up:%d\n",depth);}
                depth--;
                if(depth < 0){ break;}
                cell = stack[depth];

                if(cell == null) { break; }
                glScalef(10,10,10);
                glTranslatef(-cell->pos[0],-cell->pos[1],-cell->pos[2]);
            }
            block = cell;
            //continue;
        } else if(block->get_type() == BLOCK_TYPE_BLOCK){
//            if(_first_render){printf("if(block->get_type() == BLOCK_TYPE_CELL):else:%d\n",block);}
            glTranslatef(-block->pos[0],-block->pos[1],-block->pos[2]);
        }
        block = block->next;

    }
    _first_render = false;
}